﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Interface;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using Lamex.Common;
using Lamex.Base;

namespace Lamex.mSchedule.UI
{
    public partial class frmSCH_Internal_Order_Confirm : frmBaseChild
    {
        string strSql;
        DataTable dt;

        public frmSCH_Internal_Order_Confirm()
        {
            InitializeComponent();
        }

        private void frmSCH_Internal_Order_Confirm_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            gridControl1.UseEmbeddedNavigator = true;
        }

        private void frmSCH_Internal_Order_Confirm_Resize(object sender, EventArgs e)
        {
            splitContainerControl1.SplitterPosition = this.Width / 2;
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            //gridView1.OptionsBehavior.Editable = true;
            //gridView1.OptionsSelection.MultiSelect = true;
            //gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

            //gridView1.Columns.Clear();

            refreshGridViewData();

        }

        private void refreshGridViewData()
        {
            //刷新【Transfer_Package_List】表中MRP为"*8"的未完成入仓确数数据
            strSql = @"SELECT a.Package_Mo,Material_No,Material_Desc,MRP_Owner,Order_QTY,Confirmed_QTY,Order_QTY-ISNULL(Confirmed_QTY,0) AS Owe_QTY ,'' as CurrentlyNum
FROM
(SELECT Package_Mo,Material_No,Material_Desc,MRP_Owner,Order_QTY
FROM Transfer_Package_List
WHERE RIGHT(MRP_Owner,1)='8') AS a
LEFT JOIN 
(SELECT Package_Mo,SUM(Confirmed_QTY) AS Confirmed_QTY
FROM OP_MO_Internal_Order_Confirm
GROUP BY Package_Mo) AS b
ON a.Package_Mo=b.Package_Mo
WHERE Confirmed_QTY<Order_QTY OR Confirmed_QTY IS NULL";

            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            if (dt.Rows.Count > 0)
            {
                gridControl1.DataSource = dt;
            }

            //setGridViewAutoColumnWidth();

            //刷新当天确认数据
            strSql = @"SELECT a.Package_Mo AS 生产订单,b.Material_Desc AS 产品描述,b.Order_QTY AS 订单数量,
Confirmed_QTY AS 确认数量,UPDATE_TIME AS 确认时间,UPDATE_USER AS 确数人
FROM
(SELECT * FROM OP_MO_Internal_Order_Confirm
WHERE DateDiff(dd,UPDATE_TIME,getdate())=0) AS a
LEFT JOIN Transfer_Package_List AS b
ON a.Package_Mo=b.Package_Mo";

            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            gridControl2.DataSource = dt;

        }

        //遍历并设置自动列宽
        private void setGridViewAutoColumnWidth()
        {
            gridView1.OptionsView.ColumnAutoWidth = false;
            for (int i = 0; i < gridView1.Columns.Count; i++)
            {
                gridView1.BestFitColumns();
                if (i == 2)
                {
                    gridView1.Columns[2].Width = 10;
                }
                else
                {
                    gridView1.Columns[i].BestFit();//自动列宽    
                }
            }        
        }

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        public override void DoExport(IButtonInfo sender)
        {
            Lamex.Common.ExecelHelper.GridViewToExcel(gridView1);
            base.DoExport(sender);
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            //检查用户当前输入的是否是数字或小数点

        }

        private void sbtnConfirm_Click(object sender, EventArgs e)
        {
            //最好在用户输完【当前确数】时检查是否小于或等于【当前欠数】
            //如果不能，则在确数保存前检查gridView1【当前确数】列用户输入数字是否全部小于或等于【当前欠数】
            //如果不是，则提醒用户检查
            //如果满足条件，则将【当前确数】列数据保存到【OP_MO_Internal_Order_Confirm】表中。并提示数据保存成功
            DataTable dt = new DataTable();
            dt.TableName = "OP_MO_Internal_Order_Confirm";
            dt.Columns.Add("Package_Mo");
            dt.Columns.Add("Confirmed_QTY");
            dt.Columns.Add("UPDATE_TIME");
            dt.Columns.Add("UPDATE_USER");
            for (int i=0;i<gridView1.RowCount;i++)
            {
               string material_No= gridView1.GetRowCellDisplayText(i, "Package_Mo"); 
               string currentlyNum =gridView1.GetRowCellDisplayText(i, "CurrentlyNum");
                if (string.IsNullOrEmpty(currentlyNum)) currentlyNum = "0";
                if (int.Parse(currentlyNum)!=0)
                {
                    DataRow dr = dt.NewRow();
                    dr["Package_Mo"] = material_No;
                    dr["Confirmed_QTY"] = currentlyNum;
                    dr["UPDATE_TIME"] = DateTime.Now;
                    dr["UPDATE_USER"] = Loginer.CurrentUser.Account;
                    dt.Rows.Add(dr);
                }
            }

            if(dt.Rows.Count!=0)
            {

                string tableName = dt.TableName; ;
                string sql = "insert into " + tableName + "( ";
                string sql2 = "select ";
                string field = "";
                string field2 = "";
                foreach (DataColumn d in dt.Columns)
                {
                    field += d.ColumnName.ToString() + ",";
                    field2 += d.ColumnName.ToString() + ",";
                }
                field = field.Trim(',');
                field2 = field2.Trim(',');
                sql += field;
                sql2 += field2;

                sql += " ) ";
                sql2 += " from #" + tableName + "";
                sql = sql + sql2;
                if (string.IsNullOrEmpty(field))
                {
                    XtraMessageBox.Show("【导入表格列名称不对】");
                    return;
                }

                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                string errMsg = "";
                if (BaseBuildSql.ExecuteInsertBulkData("select  " + field + "  into #" + tableName + " from  " + tableName + " where 1!=1", ds, sql, ref errMsg))
                {
                    XtraMessageBox.Show("成功保存");
                    //this.Close();
                }
                else
                {
                    XtraMessageBox.Show(errMsg);
                }

            }

            refreshGridViewData();

        }

        
        int iRow = 0;
        private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            //iRow = e.RowHandle;
        }
        //string icurrenty = "";
        private void gridControl1_EditorKeyPress(object sender, KeyPressEventArgs e)
        {
            
            
            GridControl view = sender as GridControl;
            int m = gridView1.FocusedRowHandle;
            string s = e.KeyChar.ToString();
            if (gridView1.FocusedColumn.FieldName == "CurrentlyNum")
            {
                //if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b' )
                //{
                //    e.Handled = true;  // ban the illegal string input 
                //}
                //if (e.KeyChar == '.' ) e.Handled = true; //ban the first char.
                if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar != '.')
                {
                    e.Handled = true;  //非以上键则禁止输入
                }

                //if (gridView1.GetRowCellDisplayText(m, "CurrentlyNum") != null)
                //    icurrenty = gridView1.GetRowCellDisplayText(m, "CurrentlyNum").ToString();
                //icurrenty += e.KeyChar;
                //if (e.KeyChar == '.' && icurrenty == "") e.Handled = true; //禁止第一个字符就输入小数点
                //if (e.KeyChar == '.' && icurrenty.Contains(".")) e.Handled = true;


            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //icurrenty = "";
            int m = e.RowHandle;
            iRow = e.RowHandle;
            GridView view = sender as GridView;
            string cellData = "";
            if (view.GetRowCellDisplayText(m, "CurrentlyNum") == null)
                cellData = "";
            else
                cellData = gridView1.GetRowCellDisplayText(m, "CurrentlyNum").ToString();
            if(string.IsNullOrEmpty(cellData))return;
            decimal Owe_QTY = 0;
            if (gridView1.GetRowCellDisplayText(m, "Owe_QTY")!=null)
                Owe_QTY = decimal.Parse(gridView1.GetRowCellDisplayText(m, "Owe_QTY").ToString());
            if(decimal.Parse(cellData)>Owe_QTY)
            {
                XtraMessageBox.Show("订单号："+ gridView1.GetRowCellDisplayText(m, "Package_Mo").ToString() + " 的当前确数："+ cellData + "不能大于补料欠数："+ Owe_QTY + ""); 
                return;
            }

        }

        private void gridView1_RowClick(object sender, RowClickEventArgs e)
        {
            iRow = e.RowHandle;
        }

    }
}